package diablo3.process;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import diablo3.Config;
import diablo3.support.Util;

public class RestartD3 {
	private static final Log LOG = LogFactory.getLog(RestartD3.class);
	
	public static final String AMF = "xxx.exe";
	public static final String TNTHelper = "TNThelper.exe";
	public static final String TNT = "TNT.exe";
	public static final String D3 = "Diablo III.exe";
	private Processer processer = new Processer();
	
	/**
	 * 每1分钟扫描D3进程，如果连续超过5次没有进程，重启
	 */
	public void autoRestartD3(){
		LOG.info("启动D3重启监控程序");
		new Thread(){
			@Override  
            public void run(){
				int deadCount = 0;
				while(true){
					if(processer.getProcess(D3) == null){
						deadCount++;
						LOG.info("deadCount:" + deadCount);
					}
					else{
						deadCount = 0;
					}
					if(deadCount >= 5){
						restartD3All();
						deadCount = 0;
					}
					Util.threadSleep(60);
				}
			}
		}.start();
	}
	
	/**
	 * 每分钟循环重启AMF
	 */
	public void reestartAMFCycle(){
		LOG.info("启动循环重启AMF程序");
		new Thread(){
			@Override  
            public void run(){
				while(true){
					restartAMF();
					Util.threadSleep(120);
				}
			}
		}.start();
	}
	
	
	public void restartD3All(){
		LOG.info("开始重启D3");
		processer.killProcess(AMF);
		processer.killProcess(TNTHelper);
		processer.killProcess(TNT);
		processer.killProcess(D3);
		
		startD3All();
	}
	
	public void startD3All(){
		Util.threadSleep(2);
		processer.startProcess(Config.Processer.TNTPath + AMF);
		Util.threadSleep(20);
		processer.startProcessInPath(Config.Processer.TNTHelperPath + TNTHelper);
	}
	
	public void restartAMF(){
		processer.killProcess(AMF);
		Util.threadSleep(2);
		processer.startProcess(Config.Processer.TNTPath + AMF);
	}
}
